package com.imgrate.migration.controller;

import com.imgrate.migration.entity.BackupTask;
import com.imgrate.migration.service.BackupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/backups")
@RequiredArgsConstructor
@Slf4j
public class BackupController {
    
    private final BackupService backupService;
    
    @PostMapping
    public ResponseEntity<BackupTask> createBackupTask(@RequestBody BackupTask task) {
        try {
            BackupTask createdTask = backupService.createBackupTask(task);
            return ResponseEntity.ok(createdTask);
        } catch (Exception e) {
            log.error("创建备份任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping
    public ResponseEntity<List<BackupTask>> getAllBackupTasks() {
        try {
            List<BackupTask> tasks = backupService.getAllTasks();
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            log.error("获取备份任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<BackupTask> getBackupTaskById(@PathVariable Long id) {
        try {
            Optional<BackupTask> task = backupService.getTaskById(id);
            if (task.isPresent()) {
                return ResponseEntity.ok(task.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取备份任务详情失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<BackupTask> updateBackupTask(@PathVariable Long id, @RequestBody BackupTask task) {
        try {
            // 为了安全，我们不直接更新整个任务，只更新特定字段
            Optional<BackupTask> existingTaskOpt = backupService.getTaskById(id);
            if (!existingTaskOpt.isPresent()) {
                return ResponseEntity.notFound().build();
            }
            
            BackupTask existingTask = existingTaskOpt.get();
            existingTask.setTaskName(task.getTaskName());
            existingTask.setSourceServerId(task.getSourceServerId());
            existingTask.setSourceServerName(task.getSourceServerName());
            existingTask.setSourcePath(task.getSourcePath());
            existingTask.setTargetType(task.getTargetType());
            existingTask.setTargetServerId(task.getTargetServerId());
            existingTask.setTargetServerName(task.getTargetServerName());
            existingTask.setTargetPath(task.getTargetPath());
            existingTask.setTargetBucket(task.getTargetBucket());
            existingTask.setTargetAccessKey(task.getTargetAccessKey());
            existingTask.setTargetSecretKey(task.getTargetSecretKey());
            existingTask.setTargetEndpoint(task.getTargetEndpoint());
            existingTask.setScheduleType(task.getScheduleType());
            existingTask.setScheduleCron(task.getScheduleCron());
            existingTask.setScheduleTime(task.getScheduleTime());
            existingTask.setScheduleDay(task.getScheduleDay());
            existingTask.setDescription(task.getDescription());
            
            BackupTask updatedTask = backupService.createBackupTask(existingTask);
            return ResponseEntity.ok(updatedTask);
        } catch (Exception e) {
            log.error("更新备份任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBackupTask(@PathVariable Long id) {
        try {
            backupService.deleteTask(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("删除备份任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PostMapping("/{id}/execute")
    public ResponseEntity<String> executeBackupTask(@PathVariable Long id) {
        try {
            Optional<BackupTask> taskOpt = backupService.getTaskById(id);
            if (!taskOpt.isPresent()) {
                return ResponseEntity.notFound().build();
            }
            
            // 开始执行备份任务
            backupService.executeBackup(id);
            return ResponseEntity.ok("备份任务已启动");
        } catch (Exception e) {
            log.error("执行备份任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("执行备份任务失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/status/{status}")
    public ResponseEntity<List<BackupTask>> getBackupTasksByStatus(@PathVariable String status) {
        try {
            List<BackupTask> tasks = backupService.getAllTasks().stream()
                .filter(task -> status.equals(task.getStatus()))
                .toList();
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            log.error("根据状态获取备份任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
}